<?php
/**
 * Helper to generate general html output
 *
 * PHP versions 4 and 5
 *
 * TutoriumBase (http://tutoriumbase.my-reality.de)
 * Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 *
 *
 * @copyright     Copyright 2012, Miguel Gonzalez (http://my-reality.de)
 * @link          http://tutoriumbase.my-reality.de TutoriumBase
 * @since         TutoriumBase v 0.1
 */

class LayoutHelper extends AppHelper {
    
    var $helpers = array('Html', 'Form', 'Session', 'Popup');
    
    
    /**
     * Generate a TinyMCE editor
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateTinyMCE() {
        $content = '<script language="javascript" type="text/javascript" src="' . $this->webroot . '/js/tiny_mce/tiny_mce.js"></script>
                    <script language="javascript" type="text/javascript">
                        tinyMCE.init({
                            theme : "advanced",
                            mode : "textareas",
                            theme_advanced_toolbar_location : "top",
                            theme_advanced_toolbar_align : "left",
                            theme_advanced_statusbar_location : "bottom",
                            theme_advanced_resizing : true,
                            skin : "o2k7",
                            skin_variant : "silver",
                            content_css : "' . $this->webroot . '/css/layout.css",
                        });
                    </script>';
        
        return $content;
    }
    
    
    
       
    
    /**
     * Generate an avatar image of the user
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function getAvatarFromUser($user) {
        $image_path = $this->webroot . 'files/avatars/' . $user['avatar'];
        $content = '<img id="avatar" src="' . $image_path . '"/>';        
        return $content;
    }
    
    
    
    
    /**
     * Generate a searchbar to searching for tutorials
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateSearch($categories) {        
        $items = array();
        
        // Liste befuellen
        for ($i = 0; $i != count($categories); ++$i) {
            if (count($categories[$i]['CategoryCount'])) {
                $items[$i] = $categories[$i]['Category']['name'] . ' (' . count($categories[$i]['CategoryCount']) . ')';
            }
        }
        
        $content = '<div id="search">' .
                   $this->Form->create('Tutorial', array('action' => 'search')) .
                   $this->Form->input('category', 
                           array('type' => 'select', 
                                 'options' => $items,
                                 'label' => false)) .
                   $this->Form->input('searchword', array('label' => false)) .
                   $this->Form->submit('', array('class' => 'button_blue', 'id' => 'TutorialSearch')) .
                   $this->Form->end() .
                   '</div>';
        
        $content .= $this->Popup->generate('TutorialSearch', 'TutoriumBase durchsuchen', 0);
        
        // Initializing input fields
        $content .= '<script type="text/javascript">
                        setDefaultInput("Alle Kategorien", "TutorialCategory");
                        setDefaultInput("Tutorial suchen...", "TutorialSearchword");
                     </script>';
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a dropdown menu
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateDropdown($caption, $inbox) {        
       $content = '<div class="dropdown">
                    <div class="button"><div class="caption">' . $caption . '</div>
                        <div class="arrow"></div>
                    </div>                    
                    <div class="dropbox">' . $inbox . '</div>
                  </div>';        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a Login form
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateLogin() {        
        $content = '<div id="loginform">' . $this->Form->create('User', array('action' => 'login'));        
        $content .= $this->Form->input('username', array('label' => 'Username'));
        $content .= $this->Form->input('password', array('type' => 'password', 'label' => 'Passwort'));
        $content .= $this->Form->submit('Anmelden', array('class' => 'button_blue'));
        $content .= $this->Form->end() . '</div>';
        
        // Animation
        $content .= '<script type="text/javascript">
                        setDefaultInput("Benutzername", "UserUsername");
                        setDefaultInput("Passwort", "UserPassword");
                     </script>';
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate an icon link
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function iconLink($caption, $link, $icon, $classes = array()) {        
        $content = '<div class="iconLink';
        
        foreach ($classes as $class) {
            $content .= ' ' . $class;
        }
        
        $content .= '"><div class="icon">
                            <img src="' . $this->webroot . 'img/icons/' . $icon . '"\>
                       </div>
                     <div class="caption">' . $caption . '</div>';
        
        
        $content .= '</div>';
        
        return $this->Html->link($content, $link, array('escape' => false, 'nohtml' => false));
    }
    
    
    
    
    
    /** 
     * Generate a link menu
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     * 
     * Array-Structure:
     * 
     * array(
     *      "Caption1" => array(
     *                      "icon" => "iconname",
     *                      "link" => "linkname"
     *                    ),
     *      "Caption2" => array(
     *                      "icon" => "iconname",
     *                      "link" => "linkname"
     *                    )
     *      )
     */
    function linkMenu($data = array()) {
        
        $content = '';
        
        if (empty($data)) {
            return;
        }
        
        foreach ($data as $key => $record) {
            $content .= $this->iconLink($key, $record['link'], $record['icon'], array('menuItem'));
        }
        
        return $content;
    }
    
    
    
    
    
    /**
     * Show an animated category box
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function showCategoryBox($categories) {
        $category_string = '';  
        
        // Looking for the highest size
        $temp_sizes = array();        
        for ($i = 0; $i != count($categories); ++$i) {
            $temp_sizes[$i] = count($categories[$i]['CategoryCount']);
        }
        foreach ($categories as $category) {       
            // Align size
            if (count($category['CategoryCount'])) {
                $percent = count($category['CategoryCount']) * 100 / max($temp_sizes);
                
                // Transfer information to jQuery
                $content = '<span class="category"><span class="' . $percent . '"></span>' . $category['Category']['name'] . '</span> ';
                $category_string .= $this->Html->link($content, array(
                                                        'controller' => 'categories', 
                                                        'action' => 'view/' . $category['Category']['id']),
                                                                array(
                                                        'escape' => false)
                                                     );
            }
        }
        
        return $category_string;
    }
    
    
    
    
    
    /**
     * Show a animated tutorial information box
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateTutorialInfo($tutorial) {
        // Initializing
        $content = '';
        
        if (is_array($tutorial) && !empty($tutorial)) {
            
            // Admin check
            $admin = $this->Session->read('Auth.User.id') == $tutorial['User']['id'];
            
            // Caption
            $content .= '<div class="description_box">';
            
            if ($admin)
            {
                $content .= '<div class="admin_buttons">';
                // "Add Chapter" button
                $content .= $this->Html->link('Kapitel hinzufuegen', array(
                                                    'controller' => 'chapters',
                                                    'action'     => 'add/' . $tutorial['Tutorial']['id']),
                                                                     array(
                                                    'class' => 'button_green tut_button left_elem_top'
                                              )
                            );
                
                // "edit tutorial" button
                $content .= $this->Html->link('Tutorial bearbeiten', array(
                                                    'controller' => 'tutorials',
                                                    'action'     => 'edit/' . $tutorial['Tutorial']['id']),
                                                                     array(
                                                    'class' => 'button_blue tut_button center_elem_top'
                                             )
                            );
                
                // "delete tutorial" button
                $content .= $this->Html->link('Tutorial loeschen', array(
                                                    'controller' => 'tutorials',
                                                    'action'     => 'delete/' . $tutorial['Tutorial']['id']),
                                                                   array(
                                                    'class' => 'button_red tut_button right_elem_top'
                                             )                        
                            );
                
                $content .= '</div>';
            }
            
            // Path to the rating image
            $image_path = $this->webroot . 'img/content/rating.png';
            
            // Create a relative fixed background grid            
            $bg_categories = '<div class="background-categories">';
            foreach ($tutorial['Category'] as $category) {
                $bg_categories .= '<div class="background-category">' . $category['Category']['name'] . '</div>';
            }            
            $bg_categories .= '</div>';
            
            $content .= '<div class="topcontent">' 
                            . $bg_categories .
                            '<div class="transparent">
                                <div class="caption">' . $tutorial['Tutorial']['caption'] . '</div>
                                <div class="rating"><img src="' . $image_path . '"/></div>
                                <div class="autorinfo">' . $tutorial['Tutorial']['description'] . '</div>
                            </div>
                         </div>';
            
            $content .= $this->generateChapterBar($tutorial['Chapter'], $admin);
            $content .= '</div>';
        }
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a box with bookmarks inside
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateUserBookmarks($user, $id) {
        $content = '';        
        // Bookmarks (Networks) 
        $bookmarks = '';        
        $username = $this->getFullName($user);
        
        // RSS
        $bookmarks .= $this->Html->link('', 
                                        '#', 
                                        array(
                                            'class'  => 'bookmark rss',
                                            'id'     => 'rss_' . $id,
                                            'target' => '_blank'
                                        ));
        // Twitter
        if (!empty($user['twitter']))
        {
            $bookmarks .= $this->Html->link('', 
                                            'http://twitter.com/' . $user['twitter'], 
                                            array(
                                                'class'  => 'bookmark twitter',
                                                'id'     => 'twitter_' . $id,
                                                'target' => '_blank'
                                            ));
        }          

        // Facebook
        if (!empty($user['facebook']))
        {
            $bookmarks .= $this->Html->link('', 
                                            'http://facebook.com/' . $user['facebook'], 
                                            array(
                                                'class'  => 'bookmark facebook',
                                                'id'     => 'facebook_' . $id,
                                                'target' => '_blank'
                                            ));
        }

        // Google+
        if (!empty($user['goplus']))
        {
            $bookmarks .= $this->Html->link('', 
                                            'https://plus.google.com/' . $user['goplus'], 
                                            array(
                                                'class'  => 'bookmark googleplus',
                                                'id'     => 'googleplus_' . $id,
                                                'target' => '_blank'
                                            ));
        }

        // Skype
        if (!empty($user['skype'])) {
            $bookmarks .= '<script type="text/javascript" src="http://download.skype.com/share/skypebuttons/js/skypeCheck.js"></script>';
            $bookmarks .= $this->Html->link('', 
                                            'skype:' . $user['skype'] . '?call', 
                                            array(
                                                'class'  => 'bookmark skype',
                                                'id'     => 'skype_' . $id,
                                                'target' => '_blank'
                                            ));
        }
            
        $content .= '<div class="bookmarks">' . $bookmarks . '</div>';        
        
        // Register popups
        $content .= $this->Popup->generate('rss_' . $id, $username . ' abonnieren', 1);
        $content .= $this->Popup->generate('facebook_' . $id, $username . ' auf Facebook', 1);
        $content .= $this->Popup->generate('twitter_' . $id, $username . ' auf Twitter', 1);
        $content .= $this->Popup->generate('googleplus_' . $id, $username . ' auf Google+', 1);
        $content .= $this->Popup->generate('skype_' . $id, $username . ' bei Skype', 1);
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a box with user information
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateUserInformation($user, $global_id, $small = true) {
        $content = '<div class="avatar_box">';        
        $username = $this->getFullName($user);
        
        $content .= $this->Html->link('<div class="avatar">' . $this->getAvatarFromUser($user) . '</div>', 
                                        array('controller' => 'users',
                                                'action'    => 'view/' . $user['id']), 
                                        array('escape' => false, 'target' => '_blank'));
        $content .= '<div class="name">' . $username . '</div>'; 
        $content .= $this->generateUserBookmarks($user, $global_id);                    
        $content .= '</div>';
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a dynamic chapter bar
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateChapterBar($data, $admin, $inner_order = null) {
        $content = '';
        
        // List chapters
        $content .= '<div class="chapters"><ul>';
        for ($i = 0; $i != count($data); ++$i) { 
            // Linktyp festlegen
            if (count($data) == 1) {
                $specific = 'complete_elem';
            } elseif ($i == 0) {
                $specific = 'left_elem';
            } elseif ($i > 0 && $i < count($data) -1) {
                $specific = 'center_elem';
            } else {
                $specific = 'right_elem';
            }
            
            $buttons = '';

            if ($admin) {
                $btn_content =  '<div class="chap_button btn_edit">e</div>';

                // Edit chapter
                $buttons = $this->Html->link($btn_content, array(
                                        'controller' => 'chapters',
                                        'action'     => 'edit/' . $data[$i]['id']),
                                        array(
                                            'class'  => 'button_blue',
                                            'escape' => false
                                        )
                            );

                $btn_content =  '<div class="chap_button btn_delete">x</div>';

                // Delete chapter
                $buttons .= $this->Html->link($btn_content, array(
                                        'controller' => 'chapters',
                                        'action'     => 'delete/' . $data[$i]['id']),
                                        array(
                                            'class'  => 'button_red',
                                            'escape' => false
                                        )
                            );
            }

            // Customize the description
            $caption = 'Teil ' .($i + 1);
            
            if (count($data) == 1) {
                $caption = 'Zum Tutorial';
            }

            // Unique ID
            $link_id = 'link_' . str_replace(' ', '_', $data[$i]['created']) . '_' . $i;
            $link_id = str_replace('-', '_', str_replace(':', '_', $link_id));

            $features = '';

            // Check, if current position have to be shown
            if ($inner_order == $data[$i]['inner_order']) {
                $features = 'hover';
            } 

            $popup_text = $data[$i]['caption'];                

            $content .= $this->Html->link('<li id="' . $link_id . '" class="' . $specific . ' ' . $features . '">'
                            . $caption . '<div class="buttons">' . $buttons . '</div>'
                            . '<span class="' . count($data) . '"></span></li>', 
                            array('controller' => 'tutorials', 
                                    'action' => 'view/' . $data[$i]['tutorial_id'] 
                                                    . '/' . $data[$i]['inner_order']),
                            array('escape' => false, 'class' => 'chap_link'));    

            // Set popups
            $content .= $this->Popup->generate($link_id, $popup_text, 1);
        }            

        $content .= '</ul></div>';

        // Animate with jQuery
        $content .= '<script type="text/javascript">javascript:initChapterBar();</script>';
        return $content;
    }
    
    
    
    
    
    /**
     * Show the right user box with tutorial information
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateTutorialFeatures($tutorial, $inner_order = null) {
        $content = '<div id="tutorial_features">';        
        $content .= $this->generateUserInformation($tutorial['User']);
        $content .= '</div>';        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate the top bar with all relevant items
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateTopbar($categories, $user) {
        $content = '<div id="topbar"><div id="left">';
        
        // Left banner
        $leftimage = $this->Html->link($this->Html->image('banner_small.png'), array('controller' => 'tutorials', 'action' => 'index'),
                                        array('escape' => false));
        
        // Right banner
        $startmenu = array('Informationen' => array(
                                    'icon' => 'ico_info.png',
                                    'link' => array('controller' => 'pages', 'action' => 'about')                                    
                                    ),
                           'Tutorials der Woche' => array(
                                    'icon' => 'ico_week.png',
                                    'link' => array('controller' => 'tutorials', 'action' => 'index/listweek')
                                    )
                          );   
        
        $content .= $this->generateDropdown($leftimage, $this->linkMenu($startmenu));      
        
        // If user is logged in
        if (is_array($this->Session->read('Auth.User'))) {
            $content .= $this->Html->link('<div id="new_tutorial" class="button_green">Neues Tutorial</div>', 
                    array('controller' => 'tutorials', 'action' => 'add'), 
                    array('escape' => false));         
            $content .= $this->Popup->generate('new_tutorial', 'Erstellt ein neues Tutorial', 0);        
        }
        $content .= '</div>'; // Left        
        $content .= '<div id="right">';        
        $content .= $this->generateSearch($categories);        
        
        if (!empty($user)) {
            // Right user menu
            $usermenu = array('Kontoeinstellungen' => array(
                                        'icon' => 'ico_settings.png',
                                        'link' => array('controller' => 'users', 'action' => 'edit/' . $user['id'])
                                        ),
                            'FAQ' => array(
                                        'icon' => 'ico_faq.png',
                                        'link' => array('controller' => 'questions', 'action' => 'view')
                                        ),
                            'Abmelden' => array(
                                        'icon' => 'ico_logout.png',
                                        'link' => array('controller' => 'users', 'action' => 'logout')
                                        ),
                            );
        
            $name = $this->getAvatarFromUser($user);

            // Show username
            if (empty($user['firstname']) || empty($user['lastname'])) {
                $name .= $user['username'];
            } else {            
                $name .= $user['firstname'] . ' ' . $user['lastname'];
            }

            $content .= $this->generateDropdown($this->Html->link($name, array('controller' => 'users', 'action' => 'view/' . $user['id']),
                                                                array('escape' => false)), 
                                                                $this->linkMenu($usermenu));
        } else {
            $content .= $this->generateDropdown('Anmelden', $this->generateLogin(), false);
        }
        
        $content .= '</div></div>';
        
        return $content;
    }
    
    
    
    
        
    /**
     * Generate the site footer
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateFooter($tmp_categories, $tmp_tutorials) {
        $content = '<div id="footer_content">';       
        
        // Footer links
        $tutoriumbase = array();
        
        // General information
        $tutoriumbase[] = $this->Html->link('Unser Prinzip', 
                                            array('controller' => 'pages',
                                                  'action'     => 'about'));        
        // Version history
        $tutoriumbase[] = $this->Html->link('Versionsgeschichte', 
                                            array('controller' => 'versions',
                                                  'action'     => 'index'));        
        // Registration
        if (!is_array($this->Session->read('Auth.User'))) {
            $tutoriumbase[] = $this->Html->link('Registrieren', 
                                                array('controller' => 'users',
                                                      'action'     => 'register'));
        }
        
        $categories = array();   
        
        $limit = 5;
        
        // Limit data
        if ($limit > count($tmp_categories)) {
            $limit = count($tmp_categories);
        }        
        
        for ($i = 0; $i != $limit; ++$i) {
            if (count($tmp_categories[$i]['CategoryCount'])) {
                $categories[] = $this->Html->link($tmp_categories[$i]['Category']['name'], 
                                                array('controller' => 'categories',
                                                        'action'     => 'view/' . $tmp_categories[$i]['Category']['id']));
                }
        }   
        
        $tutorials = array();
        
        // Build tutorial array
        foreach($tmp_tutorials as $tutorial) {
            $tutorials[] = $this->Html->link($tutorial['Tutorial']['caption'], 
                                                array('controller' => 'tutorials',
                                                        'action'     => 'view/' . $tutorial['Tutorial']['id'] . '/1'));
        }
        
        // General footer links
        $links = array();
        $links[] = $this->Html->link('CakePHP', 'http://cakephp.org', array('target' => 'blank_'));
        $links[] = $this->Html->link('Entwickler-Blog', 'http://my-reality.de', array('target' => 'blank_'));
        $links[] = $this->Html->link('JQuery', 'http://jquery.org', array('target' => 'blank_'));
        
        // Footer contact links
        $contacts = array();
        $contacts[] = $this->Html->link('Impressum', 
                                        array('controller' => 'pages',
                                              'action'     => 'impressum'));
        $contacts[] = $this->Html->link('Twitter', 'http://twitter.com/tweetmyreality', array('target' => 'blank_'));
        $contacts[] = $this->Html->link('Facebook', 'http://facebook.com/myrealityde', array('target' => 'blank_'));
        
        // Set links
        $content .= $this->generateFooterBox('TutoriumBase', $tutoriumbase);
        $content .= $this->generateFooterBox('Kategorien', $categories);
        $content .= $this->generateFooterBox('Neue Tutorials', $tutorials);  
        $content .= $this->generateFooterBox('Links', $links);
        $content .= $this->generateFooterBox('Kontakt', $contacts, true);
        
        // Set site information (bottom of the page)
        Configure::load('configuration');
        $about = Configure::read('About');        
        $cake_icon = $this->Html->link('<img id="cakelink" src="' . $this->webroot . 'img/cake.power.gif"/>',
                                       'http://cakephp.org', array('escape' => false, 'target' => 'blank_'));        
        $content .= '<div id="site_description"><div class="left">Programming and Design by ' 
                    . $about['author'] . ', &copy; ' . $about['year'] . ' '
                    . $about['name'] . ' | ' . $this->Html->link('Impressum', array('controller' => 'pages',
                                                                                    'action' => 'impressum')) . '<div id="version">Version ' . $about['version'] . '</div></div>
                        
                    <div class="right">' . $cake_icon .'</div></div>';
        $content .= '</div>';        
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a single footer box
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateFooterBox($caption, $data, $last = false) {
        if (empty($data)) {
            return '';
        }
        
        $content = '<div class="footer_box';
        
        if ($last) {
            $content .= ' last';
        }
        
        $content .= '">';        
        $content .= '<div class="caption">' . $caption . '</div>';
        
        // Content
        foreach ($data as $element) {
            $content .= '<div class="element">' . $element . '</div>';
        }        
        
        $content .= '</div>';
        
        return $content;
    }
    
    
    
    
    
    /**
     * Generate a short tutorial box
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateShortTutorialInfo($data) {
        $content = '<div id="leftbox">';
        
        $content .= '</div>';
        
        return $content;
    }    
        
    
    
    
    
    /**
     * Generate detailed user information
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function generateExtendedUserInformation($user_data, $data, $mode = 0) {
        $content = '<div id="current_user_information">';  
        
        $content .= '</div>';
        
        return $content;
    }
    
    
    
    
    
    /**
     * Return the real name
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.1
     */
    function getFullName($user) {
        $username = '';
        
        if (!empty($user['firstname']) && !empty($user['lastname'])) {
            $username = $user['firstname'] . ' ' . $user['lastname'];
        } else {
            $username = $user['username'];
        }        
        return $username;
    }
    
    
    
    
    
    /**
     * If an error of compatibility has been detected, show a permanent dialog with 
     * an option of change the settings.
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.2
     */
    function checkCompatibility()
    {
        $content = '<div class="error_log">
                        <noscript>
                            <div class="error button_red">Javascript ist deaktiviert. Bitte schalten Sie es ein, um alle Funktionen zu nutzen.</div>
                        </noscript>
                    </div>';
        
        return $content;
    }
    
    
    
    
    
    
    /**
     * Shows the main caption
     * 
     * @author      Miguel Gonzalez
     * @since       TutoriumBase v 0.2
     */
    function generateMainCaption($text) {
        
        $content = '';
        if (!empty($text)) {
            $content .= '<div class="caption_main">' . $text . '</div>';
        }
        
        return $content;
    }
}

?>
